export const key = 'goodsdata';
export var valueobj = {goodsid:0,count:0};
export  function getItem(){
    var obj = localStorage.getItem(key);
    obj = obj || '[]';
    return JSON.parse(obj);
}
export function setItem(value){
    var obj = localStorage.getItem(key);
    obj = obj || '[]';
    var arr = JSON.parse(obj);
    arr.push(value);
    localStorage.setItem(key,JSON.stringify(arr));
}

export function getobj(){
    var arr = getItem();
    var resobj = {};
    for(var i=0;i<arr.length;i++){
        var item = arr[i];
        if(!resobj[item.goodsid]){
            resobj[item.goodsid]=item.count;
        }else{
            var count = resobj[item.goodsid];
            resobj[item.goodsid]= count + item.count;
        }
    }
    return resobj;
}
export function updatedata(obj){
    var arr  = getItem();

    var count = 1;
    if(obj.type =='add'){
        //加
        arr.push({goodsid:obj.goodsid,count:count});
    }else{
        //减
        for(var i =0 ;i < arr.length ; i++){
            //如果这个对象中的count值等于1，则删除这个对象，否则将这个对象的count减1以后保存回去
            if(arr[i].goodsid == obj.goodsid){
                if(arr[i].count > 1){
                    arr[i].count = arr[i].count -1;
                    break;
                }else{
                    //删除此对象
                    arr.splice(i,1);
                    break;
                }
            }
        }
    }

//    将最新的arr保存回localStorage中
    localStorage.setItem(key,JSON.stringify(arr));

}

export function removeItem(goodsid){
    var arr = getItem(key);
    for(var i= arr.length -1;i>=0 ; i--){
        if(arr[i].goodsid == goodsid){
            arr.splice(i,1);
        }
    }
    localStorage.setItem(key,JSON.stringify(arr));

}
